package com.monster.starter.core.filter;

import com.monster.common.Context;
import com.monster.starter.core.common.config.http.HttpConfig;
import com.monster.starter.core.common.entity.MonsterHttpServletRequest;
import com.monster.starter.core.utils.RequestUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 上下文初始化拦截器
 * 这里面只包含数据的初始化
 *
 * @author kuang
 */
@Component
@Order(Integer.MIN_VALUE)
public class ContextFilter extends OncePerRequestFilter {
    /**
     * http请求的配置
     */
    @Autowired
    private HttpConfig httpConfig;

    /**
     * 请求拦截。初始化上下文
     *
     * @param request     请求对象
     * @param response    响应对象
     * @param filterChain 拦截器链路
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            Context.init();
            Context.set(HttpServletRequest.class.toString(), new MonsterHttpServletRequest(request, httpConfig.isRouteMode()));
            filterChain.doFilter(RequestUtils.get(), response);
        } finally {
            Context.clean();
        }
    }
}
